package com.kun.comfig;

import com.kun.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @className: LoginMemberFilter
 * @Description: 登录过滤器
 * @author: kunkun
 * @date: 2025/7/25 18:38
 */
@Component
public class LoginMemberFilter  implements GlobalFilter, Ordered {

    private Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 排除不需要过滤的路径
        String path = exchange.getRequest().getURI().getPath();
        if (path.contains("/admin")
            || path.contains("/hello")
            || path.contains("/member/member/login")
            || path.contains("/member/member/send-code")){
            LOG.info("不需要验证：{}",path);
            return chain.filter(exchange);
        }else {
            LOG.info("需要登录验证：{}",path);
        }
        //2. 对token进行验证---是否为空
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (token==null || token.isEmpty()){
            LOG.warn("token为空，该请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//返回401，未被授权状态码
            return exchange.getResponse().setComplete();
        }
        //3. 对token进行验证---是否正确、被修改、过期...
        boolean validate = JwtUtil.validate(token);
        if (validate){
            LOG.info("token有效，该请求被放行");
            return chain.filter(exchange);
        }else {
            LOG.warn("token无效，该请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//返回401，未被授权状态码
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
